<script lang="ts" setup>
import { reactive, ref, watchEffect } from 'vue';
import server from '@/utils/server'
import { getTimer } from '@/utils/index'
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import {EDIT, VIEW} from '@/views/config'

let myBlogCon = reactive<{
    list: any
    total: number
}>({
    list: [],
    total: 0
})
let pageTotal = ref(1)
const searchMyblog = (page: number = 1) => {
    server.get('/api/blog/searchMyblog', {
        page,
        size: 5
    }).then(res => {
        if(res.errno === 0) {
            myBlogCon.list = res.data?.list
            myBlogCon.total = res.data?.total
        }
    })
}
watchEffect(() => {
    searchMyblog(pageTotal.value)
})
const currChange = (page: number) => {
    pageTotal.value = page
}
const open = (ele: any) => {
    ElMessageBox.confirm(
        '确认删除吗?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            server.post('/api/blog/delete', {
                id: ele.id
            }).then(res => {
                if(res.errno == 1) {
                    ElMessage.error(res.message)
                    return
                }
                searchMyblog(pageTotal.value)
                ElMessage({
                    type: 'success',
                    message: res.message,
                })
            })
        })
}

const router = useRouter()
const editView = (type: string, id: number) => {
    router.push(`/newblog?type=${type}&id=${id}`)
}
</script>
    
<template>
    <div class=" max-h-max bg-white border">
        <div class="text-base p-5 border-b text-gray-800 mt-4">
            贴子列表
        </div>
        <div v-for="ele in myBlogCon.list" :key="ele.id"
            class="flex border-b justify-between items-center p-5 pt-0 text-gray-800 mt-4">
            <div class=" ">
                <p class="font-thin text-xl">{{ele.title}}</p>
                <p class="text-xs box-border mt-1 text-gray-500">更新于{{getTimer(ele.createdAt)}}</p>
            </div>
            <div>
                <el-dropdown>
                    <el-button>
                        操作
                    </el-button>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item @click="editView(EDIT, ele.id)">编辑</el-dropdown-item>
                            <el-dropdown-item @click="open(ele)">删除</el-dropdown-item>
                            <el-dropdown-item @click="editView(VIEW, ele.id)">查看</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </div>
        </div>
        <el-pagination @currentChange="currChange" :pageSize="5" background layout="prev, pager, next"
            :total="myBlogCon.total" class="mt-4" />
    </div>
</template>